using System;
using System.Collections.Generic;
using System.Collections;

namespace ObjectTransposeApi.Handler.Expand
{
	/// <summary/>
	internal class EnumeratorExpandHandler : AbstractExpandHandler
	{
		/// <summary/>
        internal override IEnumerable<object> Process(object value)
		{
			// if the object doesn't implement the enumerator interface then move on
			if (!typeof(IEnumerator).IsInstanceOfType(value))
			{
				return base._successor.Process(value);
			}

			// rather than just returning the enumerator, copy its values to a new list ... although this
			// seems like a waste of resources, it is a good idea since the lifetime of the enumerator is not known

			IEnumerator enumerator = (IEnumerator)value;

			List<object> parsedValues = new List<object>();

            try
            {
                // always reset the state of the enumerator ... cause we have no idea what it is
                enumerator.Reset();
            }
            catch (NotImplementedException)
            {
                // just ignore the error ... unfortunately this means no data will be available
            }

			// move each value into the new list
			while (enumerator.MoveNext())
			{
				parsedValues.Add(enumerator.Current);
			}

			return parsedValues;	
		}
	}
}
